package StudyCode.summary.myfile;

import java.io.*;
import java.util.Arrays;

/**
 * 版权所有 科技与人文(www.tah1986.com)
 */
public class CopyFileContentByteArray {

	public static void main(String[] args) throws IOException {
		System.out.println(Arrays.toString(copyToByteArray(new File("E:\\迅雷下载\\test1.txt"))));
	}

	private static final int BUFFER_SIZE = 4096;

	private static byte[] copyToByteArray(final File in) throws IOException {
		return copyToByteArray(new BufferedInputStream(new FileInputStream(
				in)));
	}

	private static byte[] copyToByteArray(final InputStream in) throws IOException {
		final ByteArrayOutputStream out = new ByteArrayOutputStream(
				BUFFER_SIZE);
		copy(in, out);
		return out.toByteArray();
	}

	public static int copy(final File in, final File out) throws IOException {

		return copy(new BufferedInputStream(new FileInputStream(in)),
				new BufferedOutputStream(new FileOutputStream(out)));
	}

	public static void copy(final byte[] bytes, final File file) throws IOException {
		final ByteArrayInputStream in = new ByteArrayInputStream(bytes);
		final OutputStream out = new BufferedOutputStream(new FileOutputStream(file));
		copy(in, out);
	}

	public static int copy(InputStream in, OutputStream out) throws IOException {
		if (!(in instanceof BufferedInputStream)) {
			in = new BufferedInputStream(in);
		}
		if (!(out instanceof BufferedOutputStream)) {
			out = new BufferedOutputStream(out);
		}

		int byteCount = 0;
		final byte[] buffer = new byte[BUFFER_SIZE];
		int bytesRead = -1;
		while ((bytesRead = in.read(buffer)) != -1) {
			out.write(buffer, 0, bytesRead);
			byteCount += bytesRead;
		}
		out.flush();
		return byteCount;
	}

	public static void copy(final byte[] bytes, final OutputStream out) throws IOException {
		out.write(bytes);
	}

	public static int copy(Reader in, Writer out) throws IOException {

		if (!(in instanceof BufferedReader)) {
			in = new BufferedReader(in);
		}
		if (!(out instanceof BufferedWriter)) {
			out = new BufferedWriter(out);
		}

		int byteCount = 0;
		final char[] buffer = new char[BUFFER_SIZE];
		int bytesRead = -1;
		while ((bytesRead = in.read(buffer)) != -1) {
			out.write(buffer, 0, bytesRead);
			byteCount += bytesRead;
		}
		out.flush();
		return byteCount;
	}

	public static void copy(final String in, Writer out) throws IOException {

		if (!(out instanceof BufferedWriter)) {
			out = new BufferedWriter(out);
		}
		out.write(in);
	}
}
